package stdio.costa.moca;

import java.util.Date;

import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlTransient;

import stdio.costa.Persistentable;
import stdio.costa.moca.model.User;

@MappedSuperclass
public abstract class AbstractPersistentable implements Persistentable {

	private static final long serialVersionUID = -2710945263585466701L;

	@Temporal(TemporalType.TIMESTAMP)
	@XmlTransient
	private Date createdOn;
	
	@Temporal(TemporalType.TIMESTAMP)
	@XmlTransient
	private Date updatedOn;
	
	@XmlTransient
	private String createdBy;
	
	@XmlTransient
	private String updatedBy;
	
	@PrePersist
	protected void onPrePersist() {
		setCreatedOn(new Date());
		if(getClass() != User.class) {
			User user = ThreadLocalSessionManager.getUser();
			if(user != null) {
				setCreatedBy(user.getUuid());
			}
		}
	}
	
	@PreUpdate
	protected void onPreUpdate() {
		setUpdatedOn(new Date());
		User user = ThreadLocalSessionManager.getUser();
		if(user != null) {
			setUpdatedBy(user.getUuid());
		}
	}
	
	@Override
	public Date getCreatedOn() {
		return createdOn;
	}

	@Override
	public void setCreatedOn(Date createTime) {
		this.createdOn = createTime;
	}

	@Override
	public Date getUpdatedOn() {
		return updatedOn;
	}

	@Override
	public void setUpdatedOn(Date updatedOn) {
		this.updatedOn = updatedOn;
	}

	@Override
	public String getCreatedBy() {
		return createdBy;
	}

	@Override
	public void setCreatedBy(String createdBy) {
		this.createdBy = createdBy;
	}

	@Override
	public String getUpdatedBy() {
		return updatedBy;
	}

	@Override
	public void setUpdatedBy(String updatedBy) {
		this.updatedBy = updatedBy;
	}
}
